package com.biu.billiards.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biu.billiards.config.BaseErrorEnum;
import com.biu.billiards.config.BaseException;
import com.biu.billiards.model.Login.AdminLoginVo;
import com.biu.billiards.model.bo.AdminBO;
import com.biu.billiards.model.bo.AdminLoginBO;
import com.biu.billiards.model.entity.Admin;
import com.biu.billiards.mapper.AdminMapper;
import com.biu.billiards.model.vo.admin.AddAdminVo;
import com.biu.billiards.model.vo.admin.GetAdminVo;
import com.biu.billiards.model.vo.admin.UpdateAdminVO;
import com.biu.billiards.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biu.billiards.utils.RedisUtils;
import com.biu.billiards.utils.TokenUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue
 * @since 2023-09-25
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {


    @Resource
    private RedisUtils redisUtils;

    @Resource
    private AdminMapper adminMapper;



    @Override
    public AdminLoginBO tokenLogin(HttpServletRequest request) {
        String token=request.getHeader("token");
        String userAccount = TokenUtils.getAccount(token);

        //查询条件
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_account",userAccount);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if(admin==null){
            throw new BaseException(BaseErrorEnum.USER_NOT_EXISTS);

        } else{
            AdminBO adminBO = new AdminBO();
            BeanUtils.copyProperties(admin,adminBO);
            AdminLoginBO userLoginBO = new AdminLoginBO();
            userLoginBO.setAdminBO(adminBO);
            //token存入redis
            redisUtils.set("token--"+userAccount,token,3, TimeUnit.DAYS);
            userLoginBO.setToken(token);

            return userLoginBO;
        }
    }

    @Override
    public AdminLoginBO adminLogin(AdminLoginVo adminLoginVo, HttpServletRequest request) {



        if (adminLoginVo.getKey()==null || !adminLoginVo.getKey().equals(DigestUtils.md5Hex("sad214+"+adminLoginVo.getAccount()+"asfsgdksgsn1("+adminLoginVo.getPassword())
        )){
            throw new BaseException(BaseErrorEnum.SIGNATURE_NOT_MATCH);
        }



        //查询条件
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_account",adminLoginVo.getAccount());
        Admin admin = adminMapper.selectOne(queryWrapper);

        System.out.println("adminLoginVo");
        System.out.println(adminLoginVo);
        System.out.println(admin);
        if(admin==null){

            throw new BaseException(BaseErrorEnum.USER_NOT_EXISTS);

        }else if (!Objects.equals(admin.getAdminPassword(), adminLoginVo.getPassword())){

            //密码错误
//            Integer result=Integer.parseInt(errorNumber)+1;
//            errorNumber = result.toString();
//            if(redisUtils.get("errorNumber--"+userLoginVo.getUserAccount())!=null){
//                redisUtils.getAndSet("errorNumber--"+userLoginVo.getUserAccount(),errorNumber);
//            }else{
//                redisUtils.set("errorNumber--"+userLoginVo.getUserAccount(),errorNumber);
//            }

            throw new BaseException(BaseErrorEnum.PASSWORD_ERROR);
        } else{

            AdminBO adminBO = new AdminBO();
            BeanUtils.copyProperties(admin,adminBO);
            AdminLoginBO adminLoginBO = new AdminLoginBO();
            adminLoginBO.setAdminBO(adminBO);
            //包装token
            String token= TokenUtils.sign(admin.getAdminAccount());
            //token存入redis
            redisUtils.set("token--"+adminLoginVo.getAccount(),token,3, TimeUnit.DAYS);
            adminLoginBO.setToken(token);
            HttpSession session = request.getSession();
            //将数据存储到session中
            session.setAttribute("account", adminLoginVo.getAccount());
            return adminLoginBO;
        }

    }

    @Override
    public IPage<AdminBO> getAdminList(GetAdminVo getAdminVo) {
        QueryWrapper<Admin> query = new QueryWrapper<>();
        query.like("admin_account",getAdminVo.getAdminAccount());
        //新建分页条件
        Page<Admin> p = new Page<>(getAdminVo.getCurrentPage(),getAdminVo.getPageSize());
        IPage<Admin> userIPage = adminMapper.selectPage(p,query);
        IPage<AdminBO> page = new Page<>();
        List<AdminBO> adminDetailBOList = new ArrayList<>();
        for (Admin admin: userIPage.getRecords()){
            AdminBO adminDetailBO = new AdminBO();
            BeanUtils.copyProperties(admin,adminDetailBO);
            System.out.println("adminDetailBO");
            System.out.println(adminDetailBO);
            adminDetailBOList.add(adminDetailBO);
        }
        /* 将转化的BO放到的Records里面  */
        page.setRecords(adminDetailBOList);
        page.setCurrent(userIPage.getCurrent());
        page.setPages(userIPage.getPages());
        page.setPages(userIPage.getSize());
        page.setTotal(userIPage.getTotal());

        return page;
    }





    @Override
    public Boolean updateAdmin(UpdateAdminVO updateAdminVO) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("admin_account",updateAdminVO.getAdminAccount());
        Admin admin = adminMapper.selectOne(queryWrapper);


        admin.setAdminPassword(updateAdminVO.getAdminPassword());
        admin.setAdminName(updateAdminVO.getAdminName());
        admin.setAdminPhone(updateAdminVO.getAdminPhone());


        return adminMapper.update(admin, queryWrapper) == 1;
    }

    @Override
    public Boolean addAdmin(AddAdminVo addAdminVo) {
        Admin admin = new Admin();

        admin.setAdminName(addAdminVo.getAdminName());
        admin.setAdminAccount(addAdminVo.getAdminAccount());
        admin.setAdminPassword(addAdminVo.getAdminPassword());
        admin.setAdminPhone(addAdminVo.getAdminPhone());

        return adminMapper.insert(admin) == 1;
    }

    @Override
    public Boolean deleteAdmin(Integer adminId) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_id",adminId);
        return adminMapper.delete(queryWrapper) == 1;
    }
}
